package com.situ.vivamarket.intcp;

import com.situ.vivamarket.model.front.CartItem;
import com.situ.vivamarket.model.Member;
import com.situ.vivamarket.model.Order;
import com.situ.vivamarket.model.front.WishlistItem;
import com.situ.vivamarket.service.front.CartItemService;
import com.situ.vivamarket.service.OrderService;
import com.situ.vivamarket.service.front.WishlistService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

//拦截所有页面

public class FrontInterceptor implements HandlerInterceptor {
    private OrderService orderService;
    private CartItemService cartItemService;
    private WishlistService wishlistService;


    public FrontInterceptor(OrderService orderService, CartItemService cartItemService, WishlistService wishlistService) {
        this.orderService = orderService;
        this.cartItemService = cartItemService;
        this.wishlistService = wishlistService;
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        HttpSession session = req.getSession();
        Member member = (Member) session.getAttribute("current_member_login");
        if (member != null) {
 //            有账号,放入请求域，前端可调用
            req.setAttribute("member", member);
            Order order =orderService.findLastCreatedOrderByMemberId(member.getId());

//            查出用户最近的一笔未支付订单
            if (order != null) {
                req.setAttribute("lastCreatedOrder", order);
            }
//              获取所有购物车项
            List<CartItem> cartItems=cartItemService.getCartItemsByMemberId(member.getId());
            req.setAttribute("cartItems", cartItems);

//            获取所有收藏
            List<WishlistItem> wis=wishlistService.findItemsByMemberId(member.getId());
            req.setAttribute("wis", wis);


        }
        return true;
    }
}
